//
//  SYTabBar.swift
//  SYWeibo
//
//  Created by Eric on 16/7/19.
//  Copyright © 2016年 Eric. All rights reserved.
//

/**
     设置  UITabBar 的样式

*/

import UIKit
//声明协议
//使用weak 修饰 需要继承NSObjectProtocol
protocol SYTabBarDelegate:NSObjectProtocol{
//协议方法
    func composeButtonClick()

}

class SYTabBar: UITabBar {

    //声明代理
    weak var syDelegate:SYTabBarDelegate?
  //声明一个闭包
    var closure:(()->())?
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    //MARK: - 监听方法
    func buttonClick(){
    //调用闭包
        closure?()

    }

    //MARK: - 设置视图  私有的函数  外界访问不到
    private func setupUI(){
    //添加控件
        addSubview(composeButton)
    
    }

    //layoutSubview 设置子控件的frame
    override func layoutSubviews() {
        super.layoutSubviews()
        //计算UITabBarButton 宽度
        let w = UIScreen.mainScreen().bounds.width * 0.2
        var index: CGFloat = 0
        //遍历子控件  把TabBar 的 所有控件 弄出来
        for value in subviews{
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
        //设置 UITabBarButton frame
                value.frame.origin.x = index * w
                value.frame.size.width = w
                index++
                //为了给撰写按钮留位子
                if index == 2 {
                index++
                
                }
            
            }
        
        }
        //设置composeButton
        composeButton.center.x = frame.width * 0.5
        composeButton.center.y = frame.height * 0.5
        
        
    }
    
    //MARK: - 懒加载控件
    lazy var composeButton: UIButton = {
    let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named:  "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.sizeToFit()
        
       return button
    }()

  
}
